package ro.one.gaeql.impl;

import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

import ro.one.gaeql.common.JobStates;
import ro.one.gaeql.common.UpdateExecutor;
import ro.one.gaeql.model.UpdateQuery;

public class GaeUpdateExecutor implements UpdateExecutor {
	@Override
	public String execute(UpdateQuery uq) {
		JobEntity job = new JobEntity();
		job.setState(JobStates.STARTED);
		
		job.save();
		
		UpdateQueryTask task = new UpdateQueryTask(uq, job.getIdJob());
		task.setInstrumentation(new LogInstrumentation(job.getIdJob()));
		
		QueueFactory.getDefaultQueue().add(
				TaskOptions.Builder.withPayload(task).header("Host",
						BackendServiceFactory.getBackendService().getBackendAddress("worker")));
		
		return job.getIdJob();
	}

	@Override
	public String createFailedJob(String error) {
		JobEntity job = new JobEntity();
		job.setState(JobStates.STARTED);
		job.setError(error);
		job.save();
		return job.getIdJob();
	}

}
